package com.sdgakj.web.h5;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Interner;
import com.google.common.collect.Maps;
import com.sdgakj.dto.FamilyPersonDTO;
import com.sdgakj.dto.FeedDTO;
import com.sdgakj.dto.base.ResResult;
import com.sdgakj.entity.*;
import com.sdgakj.enums.EnumFeedType;
import com.sdgakj.rest.UserLoginRestController;
import com.sdgakj.service.account.ShiroDbRealm;
import com.sdgakj.service.family.ActiveService;
import com.sdgakj.service.family.FamilyService;
import com.sdgakj.service.feed.FeedService;
import com.sdgakj.service.notes.NotesService;
import com.sdgakj.service.user.UserService;
import com.sdgakj.service.person.PersonService;
import com.sdgakj.utils.LoginAdminUtil;
import com.sdgakj.utils.UserSearchFilter;
import org.apache.shiro.SecurityUtils;
import org.hibernate.type.descriptor.sql.JdbcTypeFamilyInformation;
import org.slf4j.Logger;
		import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
		import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
@RequestMapping(value = "/h5/family")
public class H5FamilyController {

	private static final String PAGE_SIZE = "10";
	private static Map<String,String> sortTypes =Maps.newLinkedHashMap();
	private static Logger logger = LoggerFactory.getLogger(UserLoginRestController.class);
	@Autowired
	private FamilyService familyService;
	@Autowired
	private PersonService personService;
	@Autowired
	private UserService userService;
	@Autowired
	private FeedService feedService;
	@Autowired
	private ActiveService activeService;


	static {
		sortTypes.put("auto", "自动");
	}
	/**
	 * 家族成员申请
	 * @return
	 */
	@RequestMapping(value="/fapply",method=RequestMethod.GET)
	public String apply(@RequestParam(value = "familyId", required = false) Long familyId,
						@RequestParam(value = "page", defaultValue = "1") int pageNumber,
						@RequestParam(value = "page.size", defaultValue = PAGE_SIZE) int pageSize,
						@RequestParam(value = "sortType", defaultValue = "auto") String sortType, Model model){
		/*Map<String, Object> searchParams =new HashMap<>();
		Page<Actives> actives = familyService.getfamilycircleByPage(searchParams,pageNumber,pageSize,"",sortType);*/
		//System.out.println(familyId);
		List<Actives> actives=activeService.getActivesByFamilyId();
		model.addAttribute("actives",actives);
		return "h5/family/familyapply";
	}

	/**
	 *  同意某个person加入某个家族
	 * */
	@RequestMapping(value = "/updatePersonFid",method = RequestMethod.POST)
	public JSONObject updatePersonFid(@RequestParam(value = "id") long id,
									  @RequestParam(value = "userId")long userId,
									  @RequestParam(value = "familyId") long familyId){
		//加入家族时先查询person是否有家族信息，若有提示已有家族无法加入其他家族，若没有则可以申请
		//先创建person实体类，在创建family实体类把family的id添加到person里边，然后交给业务逻辑update
		//把申请表的这条申请记录的状态修改成 ‘1’，表示在页面加载不出来此条申请记录

		Person person=personService.getPersonById(userId);
		Family family=familyService.getFamilyById(familyId);
//		if(family!=null) {
//		//	person.setFamily(family);//添加f_id
//			person=personService.updatePersonById(person);//改家族id}
//		//	System.out.println(person);
//		}
		Actives active=activeService.getActivesById(id);
		active.setId(id);
		active.setFamily(family);
		active.setpId(person.getId());
		active.setFaStatus(1);//设置显示状态为‘1’为不显示
		JSONObject request=new JSONObject();
		try{
			activeService.updateActive(active);//改状态
			FamilyPerson familyPerson=new FamilyPerson();
			familyPerson.setFfId(family.getId());
			familyPerson.setFfName(family.getfName());
			familyPerson.setFpId(person.getId());
			familyPerson.setCreatetime(new Timestamp(new Date().getTime()));
			familyPerson.setUpdatetime(new Timestamp(new Date().getTime()));
				familyService.saveFamilyPerson(familyPerson);
			request.put("msg","加入成功！");
		}catch (Exception e){
			request.put("msg","添加失败！");
		}
		return  request;
	}

	/**
	 *  拒绝某个person加入某个家族
	 * */
	@RequestMapping(value = "/deletePersonFid",method = RequestMethod.POST)
	public JSONObject deletePersonFid(@RequestParam(value = "id") long id){
		Actives active=new Actives();
		active.setId(id);
		JSONObject request=new JSONObject();
		try{
			activeService.deleteActiveById(id);
			request.put("msg","拒绝成功！");
		}catch (Exception e){
			request.put("msg","拒绝失败！");
		}

		return  request;
	}




	/**
	 * 家族圈列表页
	 * 通过userid获取家族信息，根据家族信息查询消息
	 * @return
	 */

	@RequestMapping(value="/fcircle",method=RequestMethod.GET)
	public String getFamilyfcircles(@RequestParam(value = "familyId") Long familyId,
									@RequestParam(value = "userId")Long userId,	Model model){
		Person person=personService.getPersonByUserId(userId);
	//	System.out.println("家族id："+person.getFamily().getId());
		Family family=familyService.getFamilyById(familyId);
		String url="";
	//	if(person.getFamily().getId()!=null && person.getFamily().getId()!=0){
		if(family!=null){
			//通过用户id 和 类型查询
			List<FeedDTO> feeds=feedService.getFamilyList(userId,family.getId(),EnumFeedType.FCIRCLE.getCode());
			model.addAttribute("feeds",feeds);
			model.addAttribute("person",person);
			url= "h5/family/fcircleList";
		}else {
			url="error/404";
		}
		return url;
	}
	/*ublic String
	(@RequestParam(value = "familyId", required = false) Long familyId,//改成userId可好？
						@RequestParam(value = "page", defaultValue = "1") int pageNumber,
						@RequestParam(value = "page.size", defaultValue = PAGE_SIZE) int pageSize,
						@RequestParam(value = "sortType", defaultValue = "auto") String sortType, Model model){
		Map<String, Object> searchParams =new HashMap<>();
		searchParams.put("EQ_id", "1");
		Page<Actives> actives = familyService.getfamilycircleByPage(searchParams,pageNumber,pageSize,"",sortType);
		model.addAttribute("actives",actives);
		return "h5/family/fcircleList";
	}*/
	/**
	 * 家族内的大事记
	 * */
	@RequestMapping(value = "/note",method = RequestMethod.GET)
	public String getNotes(@RequestParam(value = "familyId") Long familyId,Long userId,Model model){
		String url="";
		try{
			//通过用户找到其家族，若没有，声明异常给url到加入家族或者提示没有家族，
			//若有找到家族，通过家族id和tagid 找到这个家族的大事记消息集合
			Person person=personService.getPersonByUserId(userId);
			Family family=familyService.getFamilyById(familyId);
			//System.out.println(person);
			//System.out.println(person.getFamily().getId());
			if(person!=null){
				if(family!=null){
					//有家族
					List<FeedDTO> feeds=feedService.getFamilyList(person.getUser().getId(),family.getId(), EnumFeedType.DASHIJI.getCode());
				//	System.out.println(feeds.size());
					model.addAttribute("feeds",feeds);
					return "h5/feed/dashijiList";
				}else {
					model.addAttribute("0","没有家族");
					throw  new Exception("没有家族！");
				}
			}
		}catch (Exception e){
			url="error/404";
		}

		return url;
	}
	/**
	 * 家族内的分享
	 * */
	@RequestMapping(value = "/shares",method = RequestMethod.GET)
	public String getShares(@RequestParam(value = "familyId") Long familyId,Long userId,Model model){
		String url="";
		try{
			Person person=personService.getPersonByUserId(userId);
			Family family=familyService.getFamilyById(familyId);
			if(person!=null){
				if(family!=null){
					List<FeedDTO> feeds=feedService.getFamilyList(person.getUser().getId(),family.getId(), EnumFeedType.SHARE.getCode());
					model.addAttribute("feeds",feeds);
					model.addAttribute("person",person);
					return "h5/family/family_share";
				}
			}
		}catch (Exception e){
			url="error/404";
		}

		return url;
	}


	/**
	 * 搜索
	 * userId
	 * @return
	 */
	@RequestMapping(value="/seache",method=RequestMethod.GET)
	public String search(@RequestParam(value = "Id", required = false) Long Id){
		return "h5/html/seacher";
	}
	/**
	 * 扫一扫
	 * userId
	 * @return
	 */
	@RequestMapping(value="/barcode",method=RequestMethod.GET)
	public String barcode(@RequestParam(value = "Id", required = false) Long Id){
		return "h5/family/barcode_scan";
	}

	/**
	 * 家族首页
	 * @return
	 */
	@RequestMapping(value="/",method=RequestMethod.GET)
	public String toFamilyJsp(){
		return "h5/family/family";
	}

	/**
	 * 家族首页
	 * @return
	 */
	@RequestMapping(value="/family",method=RequestMethod.GET)
	public String userJsp(@RequestParam(value = "userId", defaultValue = "0",required = false) Long userId,
						  @RequestParam(value = "id",required = false,defaultValue = "0")int id, Model model){
		String url="";
	//	System.out.println(userId);
		if(userId == 0L){
			url = "h5/find/join";
		}
		Person person=personService.getPersonByUserId(userId);
		if(person!=null) {
			List<FamilyPerson> families = familyService.getFamilysByPersonId(person.getId());
			if (families == null || families.size() == 0) {
				url = "h5/find/join";
			} else {
				model.addAttribute("families",families);
				System.out.println(id);
				if(id==0){
					model.addAttribute("family", families.get(0).getFfId());
					model.addAttribute("familyName",families.get(0).getFfName());
				}
				if(id!=0){
					Family family=familyService.getFamilyById((long) id);
					System.out.println(family.getId());
					if(family!=null){
						model.addAttribute("family",family.getId());
						model.addAttribute("familyName",family.getfName());
					}
				}
				url="h5/family/family";
			}
			if(person.getUser().getId()==1){
				//如果id是 1 显示家族成员管理
				model.addAttribute("show","show");
			}
		}
		return url;
	}

	/**
	 * 家谱
	 * @return
	 */
	@RequestMapping(value="/familybook",method=RequestMethod.GET)
	public String familyBook(@RequestParam(value = "Id", required = false) Long Id,
							 @RequestParam(value = "page", defaultValue = "1") int pageNumber,
							 @RequestParam(value = "page.size", defaultValue = PAGE_SIZE) int pageSize,
							 @RequestParam(value = "sortType", defaultValue = "auto") String sortType, Model model){
		Map<String, Object> searchParams =new HashMap<>();
		Page<Familybook> familybooks = familyService.getfamilygenealogyByPage(searchParams,pageNumber,pageSize,"",sortType);
		model.addAttribute("familybooks",familybooks);
		return "h5/family/familygenealogy";
	}

	/**
	 * 家族统计
	 * @return
	 */
	@RequestMapping(value="/familydatas",method=RequestMethod.GET)
	public String familyData(@RequestParam(value = "fId", required = false,defaultValue = "1") Long fId,Model model){
		List<FamilyPerson> count=familyService.getCountByfid(fId);
		model.addAttribute("count",count.size());
		int m=0,f=0;
		int alive=0,noalive=0;
		for(FamilyPerson fp:count){
			Person person=personService.getPersonById(fp.getFpId());
			if(person!=null){
				if(person.getS().equals("M")){
					m++;
				}else {
					f++;
				}
				if(person.getAlive()==1 || person.getAlive()==null){
					alive++;
				}else {
					noalive++;
				}
			}
		}
		model.addAttribute("m",m);
		model.addAttribute("f",f);
		model.addAttribute("alive",alive);
		model.addAttribute("noalive",noalive);
		model.addAttribute("fId",fId);
		return "h5/family/familydata";
	}

	/**
	 * 家族统计
	 * @return
	 */
	@RequestMapping(value="/familydatass",method=RequestMethod.GET)
	public String familyDatadetal(@RequestParam(value = "fId", required = false) Long fId,Model model){
	//	Map<String, Object> searchParams =new HashMap<>();
	//	Page<Fstatistics> fstatistics = familyService.getfamilydateByPage(searchParams,pageNumber,pageSize,"",sortType);
	//	Fstatistics fstatisticsList = familyService.getFstatisticsList(fId);
		List<FamilyPerson> list = familyService.getPersongenerationByfid(fId);
	/*	Iterator it = getPersongenerationByfid.iterator();
		FamilyPerson familyPerson = null;
		while(it.hasNext()){
			 familyPerson = it.next();
			Long name = stu.getFfId();
		}*/
	//	System.out.println("list: "+list.size());
		List<FamilyPersonDTO> fpdto = new ArrayList<>();
		for (FamilyPerson f:list) {
			Integer count=familyService.getPersonByFfIdangeneration(f.getFfId(),f.getGeneration());
			FamilyPersonDTO familyperdto = new FamilyPersonDTO();
			if(f.getGeneration()!=null) {
				familyperdto.setGeneration(f.getGeneration().intValue());
			}
			familyperdto.setCount(count);
			fpdto.add(familyperdto);
		}
		model.addAttribute("fplist",fpdto);

		return "h5/family/familydata_detail";
	}

	/**
	 * 家族统计 男女比例
	 * @return
	 */
	@RequestMapping(value="/familydataSexs",method=RequestMethod.GET)
	public String familyDatasex(/*@RequestParam(value = "fId", required = false,defaultValue = "1") Long fId,
								@RequestParam(value = "Id", required = false,defaultValue = "1") Long Id,*/int m,int f,Model model){
/*		Map<String, Object> searchParams =new HashMap<>();
		Fstatistics fstatisticsList = familyService.getFstatisticsList(fId);
		Long fpsm = personService.personsm();
		Long fpsf = personService.personsf();
		Family family = familyService.getFamilyById(Id);
		List<FamilyPersonDTO> fpdto = new ArrayList<>();
		FamilyPersonDTO familyperdto = new FamilyPersonDTO();
        familyperdto.setFpmancount(fpsf);
		familyperdto.setFpwomancount(fpsm);
		model.addAttribute("fstatisticsList",fstatisticsList);
		model.addAttribute("family",family);
		model.addAttribute("fplist",familyperdto);*/
		model.addAttribute("m",m);
		model.addAttribute("f",f);
		return "h5/family/familydata_sex";
	}

	/**
	 * 家族统计  在世去世比例
	 * @return
	 */
	@RequestMapping(value="/familydatAlive",method=RequestMethod.GET)
	public String familyDataalive(/*@RequestParam(value = "fId", required = false,defaultValue = "1") Long fId,
								@RequestParam(value = "Id", required = false) Long Id,*/int alive,int noalive, Model model){
	/*	Map<String, Object> searchParams =new HashMap<>();
		Fstatistics fstatisticsList = familyService.getFstatisticsList(fId);
		Long alive = personService.personalive();
		Long nalve = personService.personnalive();
		List<FamilyPersonDTO> fpdto = new ArrayList<>();
		FamilyPersonDTO familyPersonDTO = new FamilyPersonDTO();
		familyPersonDTO.setFpmanalive(alive);
		familyPersonDTO.setFpmannalive(nalve);
		model.addAttribute("fplist",familyPersonDTO);
		model.addAttribute("fstatisticsList",fstatisticsList);*/
		model.addAttribute("alive",alive);
		model.addAttribute("noalive",noalive);


		return "h5/family/familydata_alive";
	}

	/**
	 * 家族统计  区域比例
	 * @return
	 */
	@RequestMapping(value="/familydatArea",method=RequestMethod.GET)
	public String familydatArea(@RequestParam(value = "Id", required = false) Long Id,
								  @RequestParam(value = "page", defaultValue = "1") int pageNumber,
								  @RequestParam(value = "page.size", defaultValue = PAGE_SIZE) int pageSize,
								  @RequestParam(value = "sortType", defaultValue = "auto") String sortType, Model model){
		Map<String, Object> searchParams =new HashMap<>();
		Page<Fstatistics> fstatistics = familyService.getfamilydateByPage(searchParams,pageNumber,pageSize,"",sortType);
		model.addAttribute("fstatistics",fstatistics);
		return "h5/family/familydata_area";
	}

	/**
	 * 家族名人
	 * @return
	 */
	@RequestMapping(value="/familyss",method=RequestMethod.GET)
	public String familyfamousp(@RequestParam(value = "id", required = false) Long Id,
								@RequestParam(value = "familyId")Long familyId,
	/*						 @RequestParam(value = "page", defaultValue = "1") int pageNumber,
							 @RequestParam(value = "page.size", defaultValue = PAGE_SIZE) int pageSize,
							 @RequestParam(value = "sortType", defaultValue = "auto") String sortType,*/ Model model){
	/*	Map<String, Object> searchParams =new HashMap<>();
		Page<User> familyfamousp = userService.getfamilyfamouspById(searchParams,pageNumber,pageSize,"",sortType);*/
		/*model.addAttribute("familyfamousp",familyfamousp);*/
		Person person=personService.getPersonByUserId(Id);
		List<FamilyPerson> list=familyService.getPersonByFfId(familyId);
		List<User> users=new ArrayList<>();
		if(list!=null){
			//通过fpid查询家族里边的user
			for(FamilyPerson f:list) {
				person = personService.getPersonById(f.getFpId());
				if (person != null) {
					if (person.getUser() != null) {
						User user = userService.getUserById(person.getUser().getId());
						users.add(user);
					}
				}
			}
	/*		for(int i=0;i<users.size();i++){
				for(int j=0;j<users.size()-i-1;j++){
					if(users.get(j).getPoint()>users.get(j+1).getPoint()){
						User r=users.get(j);
						users.set(j, users.get(j+1));
						users.set(j+1, r);
					}
				}
			}*/

			model.addAttribute("familyfamousp",users);
		}
		return "h5/family/familyfamousp";
		}

/*
	*/
/*
	* 个人页面  删除亲属
	*
	* *//*

	@RequestMapping(value="/deletefamperson",method=RequestMethod.GET)
	public String deletefaperson(@RequestParam(value = "userId", required = false) Long userId,
								@RequestParam(value = "page", defaultValue = "1") int pageNumber,
								@RequestParam(value = "page.size", defaultValue = PAGE_SIZE) int pageSize,
								@RequestParam(value = "sortType", defaultValue = "auto") String sortType, Model model){
		personService.deletePersonById(userId);
		return "h5/family/family_tree";
	}
*/


	/**
	 * 显示家族树
	 * @return
	 */
	@RequestMapping(value = "/tree", method = RequestMethod.GET)
	public String showTree(@RequestParam(value = "familyId", required = false) Long familyId,Long personId,Model model) {
		logger.info("query the family list...");
		//当前家族中的所有person数据
		/*Person p=personService.getPersonByUserId(userId);
		Family family = familyService.getFamilyById(p.getFamily().getId());
		ResResult result =new ResResult();
		Long familyId = family.getId();//家族id;
		//查询这个家族的所有成
		List<Person> personList = personService.getPersonsByFId(familyId);
		List<HashMap<String ,Object>>  nodesMapList = new ArrayList<HashMap<String ,Object>>();
		for (Person person : personList) {
			HashMap<String, Object> personMap = new HashMap<String, Object>();
			personMap.put("key", person.getId());
			personMap.put("n", person.getFamilyName() + person.getName());
			personMap.put("s", person.getS());
			if (person.getF()!=null && person.getF()!=0L){
				personMap.put("f", person.getF());
			}
			if (person.getM()!=null && person.getM()!=0L){
				personMap.put("m", person.getM());
			}
			if (person.getUx()!=null && person.getUx()!=0L){
				personMap.put("ux", person.getUx());
			}
			if (person.getVir()!=null && person.getVir()!=0L){
				personMap.put("vir", person.getVir());
			}
			nodesMapList.add(personMap);
		}
		result.setData(nodesMapList);*/
		/*model.addAttribute("nodes", personMap);
		//当前家族中的所有关系数
		model.addAttribute("root_id", family.getUserId());*/
		model.addAttribute("pId",personId);
		model.addAttribute("familyId",familyId);
		return "h5/family/family_tree";
	}
	/**
	 * 创建家族申请列表
	 * @param fId 家族的id
	 * */
	@RequestMapping(value = "/createActives",method = RequestMethod.POST)
	public void createActive(Long fId,Long userId,String content){
		Person person=personService.getPersonByUserId(userId);//问题 person表里的userid是什么时候与user表的id绑定的？暂时先按person表的id查询
		//填充属性
		Actives active=new Actives();
		active.setpId(person.getId());
		Family family=familyService.getFamilyById(fId);
		active.setFamily(family);
		active.setfaTitle(person.getName());
		active.setfaDesp(person.getDescription());
		active.setFaDesp(content);
		Timestamp ts = new Timestamp(new Date().getTime());
		active.setCreatetime(ts);
		active.setUpdatetime(ts);
		//做sava
		activeService.addActive(active);
	}

	@RequestMapping(value = "/showtree")
	public String getTreeByFamily(Long fId,Long personId,Model model){
		List<FamilyPerson> familyPerson=familyService.getPersongenerationByfid(fId);
		for(FamilyPerson f:familyPerson){
			if(f.getFpId()==personId){
				model.addAttribute("pId",personId);
			}else {
				Family family=familyService.getFamilyById(f.getFfId());
				Person person=personService.getPersonByUserId(family.getUserId());
				model.addAttribute("pId",person.getId());
			}
		}

		model.addAttribute("familyId",fId);

		return "h5/family/family_tree";
	}
	/*
 	* 删除家族树数据
 	* */
	@RequestMapping(value = "/delete",method = RequestMethod.GET)
	public String deleteFamliyPerson(Long personId, Long familyId, Model model){
		FamilyPerson familyPerson=familyService.getPersonByFIdAndPId(familyId,personId);
		if(familyPerson!=null){
			try{
				familyService.deleteFamilyPerson(familyPerson);
			//	System.out.println("删除成功！");
				model.addAttribute("familyId",familyId);
			}catch (Exception e){
				logger.error("删除亲属失败！");
			}
		}
			return "h5/family/family_tree";
	}

}
